import React, { useState } from 'react'
import { Button, Modal, Form, Input, Upload } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import { useRequest } from 'ahooks'
import { createContracts } from '@/pages/Dashboard/components/CrossChain/service'

import './New.less'

const NewContract = ({ visible, onCancel, onSuccess }) => {
  const [form] = Form.useForm()
  const [fileList, setFileList] = useState([])
  const { loading: creating, run: uploadContract } = useRequest(createContracts, { manual: true })
  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
  }
  const onOk = async() => {
    try {
      const values = await form.validateFields()
      const { name } = values
      const formData = new FormData()
      formData.append('name', name)
      formData.append('file', fileList[0])
      form.resetFields()
      setFileList([])
      await uploadContract(formData)
      onSuccess()
    } catch (e) {
      console.error(e)
    }
  }
  const beforeUpload = file => {
    setFileList([file])
    return false
  }
  const onRemove = () => {
    setFileList([])
  }
  return (
    <Modal visible={visible} title="新建合约" okText="确认" cancelText="取消" onCancel={onCancel} onOk={onOk} confirmLoading={creating}>
      <Form
        {...layout}
        form={form}
      >
        <Form.Item
          label="合约名称"
          name="name"
          rules={[{ required: true, message: '请输入合约名称' }]}
        >
          <Input placeholder="请填写版本，例v0.1" maxLength={15}/>
        </Form.Item>
        <Form.Item
          label="上传合约"
          required
        >
          <div style={{ display: 'flex' }}>
            <Form.Item
              name="file"
              extra="支持扩展名: .class"
              rules={[
                {
                  required: !fileList.length,
                  message: '请上传合约',
                },
              ]}
            >
              <Upload accept=".class" beforeUpload={beforeUpload} onRemove={onRemove} fileList={fileList}>
                <Button disabled={fileList.length > 0} icon={<UploadOutlined />}>上传合约</Button>
              </Upload>
            </Form.Item>
          </div>
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default NewContract
